package com.abo.yaas.webservice;

import javax.persistence.EntityManager;
import javax.ws.rs.Path;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.UriInfo;

import com.abo.yaas.domain.Auction;
import com.abo.yaas.domain.AuctionState;
import com.abo.yaas.domain.Category;
import com.abo.yaas.webservice.constants.Operation;
import com.abo.yaas.webservice.constants.URLConstants;
import com.abo.yaas.webservice.exceptions.InvalidCredentialsException;
import com.abo.yaas.webservice.hibernate.EntityManagerUtils;
import com.abo.yaas.webservice.hibernate.WSFilter;
import com.abo.yaas.webservice.utils.AuctionFacade;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.spi.resource.Singleton;

@Singleton
@Path(URLConstants.auctionProvider)
public class AuctionResource extends EntityResource<Auction> {

    public AuctionResource() {
        super(Auction.class);
    }

    @Override
    protected WSFilter<Auction> extractFilter(final UriInfo ui) {
        final WSFilter<Auction> filter = new WSFilter<Auction>();
        final MultivaluedMapImpl params = (MultivaluedMapImpl) ui.getQueryParameters();
        final Long categoryId = params.getFirst("categoryId", Long.class);
        final EntityManager em = EntityManagerUtils.getEntityManager();

        if (categoryId != null) {
            final Category c = em.getReference(Category.class, categoryId);
            filter.addChild(new WSFilter<Auction>("category", c, Operation.EQ, Auction.class));
        }

        final String state = params.getFirst("state");
        if ("Active".equals(state)) {
            filter.addChild(new WSFilter<Auction>("state", AuctionState.AS_ACTIVE, Operation.EQ, Auction.class));
        }

        final String title = params.getFirst("title");
        if (title != null) {
            filter.addChild(new WSFilter<Auction>("title", title, Operation.LIKE, Auction.class));
        }
        return filter;
    }

    @Override
    public Auction saveOrUpdateEntity(Auction entity, HttpHeaders headers) throws InvalidCredentialsException {
        return (entity.getId() == null) ? AuctionFacade.postNewAuction(entity) : 
            super.saveOrUpdateEntity(entity,headers);
    }
}
